//
//  HMComposeView.swift
//  WeiBo14
//
//  Created by HM on 16/3/9.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import pop

class HMComposeView: UIView {
    
    
    

    var modelArray :[HMComposeModel]?
    
    var buttons: [HMComposeBtn] = [HMComposeBtn]()
    
    var mycon: UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        frame = UIScreen.mainScreen().bounds
        backgroundColor = RandomColor()
        
        let img = getScreenShot().applyLightEffect()
        
        let imgView = UIImageView(image: img)
        
        // 添加磨砂图
        addSubview(imgView)
        // 添加文字
        addSubview(sloganView)
        
        sloganView.snp_makeConstraints { (make) in
            
            make.centerX.equalTo(self)
            make.top.equalTo(100)
        }
        
        // 添加按钮
        addChildButton()
        
    }
    
    
    // MAKR - 自定义一个方法，拿到上一级的控制器
    func show (con:UIViewController) {
        
        con.view.addSubview(self)
        
        mycon = con
        
          
        
    }
    
 
    // 截取当前屏幕的内容
    private func getScreenShot() -> UIImage {
        
        let rect = UIScreen.mainScreen().bounds
        let window = UIApplication.sharedApplication().keyWindow!
        
        // 1. 开启图形的上下文
        // 参数1: 开启上下文大小,参数2是否透明,参数3如果是0就代表截取的是实际尺寸的大小,1的话是代码是点坐标大小
        UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
        // 2. 将屏幕的内容画到上下文中
        window.drawViewHierarchyInRect(rect, afterScreenUpdates: false)
        // 3. 取到图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 4. 关闭上下文
        UIGraphicsEndImageContext()
        // 5. 返回图片
        return image
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        btnAnim(false)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64((0.4 * Double(NSEC_PER_SEC)))), dispatch_get_main_queue(), {
            self.removeFromSuperview()
        });
    }
    
    // 按钮动画
    private func btnAnim(isPullUp: Bool) {
        
        let c = isPullUp ? buttons.enumerate() : buttons.reverse().enumerate()
        
        
        for (i,v) in c {
            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            // 指定控件执行动画的最终位置
            animation.toValue = NSValue(CGPoint: CGPointMake(v.center.x, v.center.y + (isPullUp ? -330 : 330)))
            animation.springBounciness = 10 // 越大幅度越大 20 弹簧
            animation.springSpeed = 8 // 速度
            animation.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            
            v.pop_addAnimation(animation, forKey: nil) // 这个Key就是如果传递了，可以把这个动画取出来
            
            
        }

       
    }
    
    
    private func addChildButton() {
        let itemW: CGFloat = 80
        let itemH: CGFloat = 110
        let btn = HMComposeBtn()
        btn.frame.size = CGSizeMake(itemW, itemH)
        // 按钮间距
        let margin = (SCREENW - 3 * itemW)/4
        
        // 读取pilst，字典转模型
        
       let tempArray = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!)
        
        modelArray = [HMComposeModel]()
        
        for dict in tempArray! {
            
            modelArray!.append(HMComposeModel(dict: dict as! [String : AnyObject]))
        }
        
        // 全部字典转模型后
        
        for (i,v) in modelArray!.enumerate() {
    
            let col = i % 3
            let row = i / 3
            let btn = HMComposeBtn()
            btn.tag = i
            btn.frame.size = CGSizeMake(itemW, itemH)
            // 添加单击事件
            btn.addTarget(self, action: #selector(HMComposeView.presentVC(_:)), forControlEvents: .TouchUpInside)
            btn.composeModel = v
            addSubview(btn)
            // 设置btn的位置
            // 设置x值
            btn.frame.origin.x = CGFloat(col + 1) * margin + CGFloat(col) * itemW
            // y值
            btn.frame.origin.y = CGFloat(row) * (itemH + margin) + SCREENH
            
            buttons.append(btn)
            
        }
  
    }
    
    
    @objc private func presentVC(btn:HMComposeBtn) {
        
        
        UIView.animateWithDuration(1.0, animations: {
            // 当前按钮变大，别的按钮变下
            
            for value in self.buttons {
                value.alpha = 0.01
                value.transform =  value == btn ? CGAffineTransformMakeScale(2, 2) : CGAffineTransformMakeScale(0.01, 0.01)
            }
            
            }) { (_) in
                
                // 完成后弹出控制器 因为6个按钮弹出的控制器都不相同，用if switch都很聒噪，这时候用plist配置一下，给按钮模型多增加一个控制器target
                let c = btn.composeModel
                let targetClass = NSClassFromString(c!.target!)! as! UIViewController.Type
                let vc = targetClass.init()
                self.mycon?.presentViewController(HMNavgationController(rootViewController: vc), animated: true, completion: {
                    
                     self.removeFromSuperview()
                })
        }
    }
    
    // 当完全被加载到父控件的时候调用后
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        
        // 拿到6个按钮
        
       btnAnim(true)
        
    }
    
    
    // MARK: - 懒加载控件
    private lazy var sloganView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    

}
